package com.fs.uc.filter;

import com.fs.uc.base.MyResponse;
import io.quarkus.arc.log.LoggerName;
import io.quarkus.runtime.annotations.RegisterForReflection;

import javax.annotation.Priority;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.ext.Provider;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

import org.jboss.logging.Logger;

/**
 * @author 崔超
 * 2021/12/15
 */
@Priority(1)
@Provider
@RegisterForReflection
public class GlobalResponseFilter implements ContainerRequestFilter, ContainerResponseFilter {
    @LoggerName("GlobalFilter")
    Logger log;

    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
        int status = responseContext.getStatus();
        Object body = responseContext.getEntity();

        if (status > 200 && status < 300 && body == null) {
            handleVoidResp(responseContext);
            return;
        }

        if (body instanceof MyResponse || body instanceof Map) {
            return;
        }
        MyResponse<Object> myResponse = MyResponse.success(body);
        responseContext.setEntity(myResponse);
    }

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        log.info(requestContext.getUriInfo().getRequestUri());
    }

    void handleVoidResp(ContainerResponseContext responseContext) throws IOException {
        responseContext.setStatus(200);
        HashMap<String, Object> map = new HashMap<>();
        map.put("success", true);
        map.put("msg", "操作成功");
        responseContext.setEntity(map,null, MediaType.APPLICATION_JSON_TYPE);
    }
}
